package com.fanyouzhao.eshop.portal.controller;

import com.fanyouzhao.eshop.core.utils.JsonResult;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @author: fanyouzhao
 * @date: 16:43 2021/6/29
 */
@RestController
@Api(tags = "上传模块")
public class UploadController {

    //@NeedsLogin
    @RequestMapping(value = "/upload",method = {RequestMethod.GET,RequestMethod.POST})
    public JsonResult upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value="type",required = false)String type) throws IOException {
        JsonResult jsonResult = new JsonResult();
        if(file.isEmpty()){
            jsonResult.setCode("0");
            jsonResult.setMsg("不能上传空文件");
        }
        else if(file.getSize()>1024*1024){
            jsonResult.setCode("0");
            jsonResult.setMsg("文件大小不能超过1M");
        }else{
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 获取文件名后缀(带.)
            String suffix = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf(".")+1);
            if("jpg".equals(suffix) || "jpeg".equals(suffix) || "png".equals(suffix)  || "gif".equals(suffix)){
                //生成UUID名称
                String uuidName = UUID.randomUUID().toString()
                        .replaceAll("-", "");

                //上传到服务器/usr目录下的/upload目录下
                if("goods".equals(type))
                    uuidName = "goods/"+uuidName;
                if("receipt".equals(type))
                    uuidName = "receipt/"+uuidName;
                File dest = new File("/usr/upload/"+uuidName+"."+suffix);
                file.transferTo(dest);

                // 把生成的文件名返给前端
                jsonResult.setCode("1");
                jsonResult.setValue("fileName",uuidName+"."+suffix);
            }else{
                jsonResult.setCode("0");
                jsonResult.setMsg("只能上传图片格式");
            }
        }
        return jsonResult;
    }
}
